package zgrjb.snbq.teach_platform.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import zgrjb.snbq.teach_platform.dto.model.User;
import zgrjb.snbq.teach_platform.enums.BizCodeEnum;
import zgrjb.snbq.teach_platform.util.JsonData;
import zgrjb.snbq.teach_platform.util.JwtUtil;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 登录拦截器
 * 支持从cookie和Authorization header中获取JWT token
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<User> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        try {
            // 从请求中获取token（优先cookie，然后header）
            String token = JwtUtil.getTokenFromRequest(request);
            
            if (token == null) {
                log.warn("Token not found in request: {}", request.getRequestURI());
                sendUnauthorizedResponse(response, "Token not found");
                return false;
            }

            // 验证token
            Claims claims = JwtUtil.checkJWT(token);
            if (claims == null) {
                log.warn("Invalid token for request: {}", request.getRequestURI());
                sendUnauthorizedResponse(response, "Invalid token");
                return false;
            }

            // 解析用户信息
            User user = JwtUtil.parseUserFromClaims(claims);
            if (user == null) {
                log.warn("Failed to parse user from token for request: {}", request.getRequestURI());
                sendUnauthorizedResponse(response, "Invalid user info");
                return false;
            }

            // 将用户信息存储到ThreadLocal中
            threadLocal.set(user);
            log.info("User authenticated: {} ({})", user.getName(), user.getType());
            
            return true;
            
        } catch (Exception e) {
            log.error("Authentication error for request: {}, error: {}", request.getRequestURI(), e.getMessage());
            sendUnauthorizedResponse(response, "Authentication failed");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理ThreadLocal，防止内存泄漏
        threadLocal.remove();
    }

    /**
     * 发送未授权响应
     */
    private void sendUnauthorizedResponse(HttpServletResponse response, String message) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        
        JsonData jsonData = JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN);
        jsonData.setMsg(message);
        
        PrintWriter writer = response.getWriter();
        writer.print(new ObjectMapper().writeValueAsString(jsonData));
        writer.close();
    }

    /**
     * 获取当前登录用户
     */
    public static User getCurrentUser() {
        return threadLocal.get();
    }
} 